var tree;
var ds,grid;

var buildTree = function(){
    var root = new Ext.tree.AsyncTreeNode({
        id:'0',
        text:'区域树'
    });
    tree = new Ext.tree.TreePanel({
        loader:new Ext.tree.TreeLoader({dataUrl:'zone!getTrees.action'}),
        root:root,
        renderTo:'tree',
        border:false,
        autoScroll:true
    });
    tree.on('click',function(node){
        node.expand();
        node.select();
        ds.load({params:{parent_id:node.id}});
    });
    tree.on('beforeload',function(node){
        tree.loader.dataUrl = 'zone!getTrees.action?parent_id='+node.id;
    });
    root.expand();
    root.select();
};

var buildGrid = function(){
    ds = new Ext.data.Store({
        proxy:new Ext.data.HttpProxy({url:'zone!getChildren.action'}),
        reader:new Ext.data.JsonReader({idProperty: "zone.id"},['zone.id','zone.name','zone.position','zone.code','zone.peopleNum'])
    });
    grid = new Ext.grid.EditorGridPanel({
        store:ds,
        columns:[
            new Ext.grid.RowNumberer(),
            {header:'名称',width:150,sortable:true,dataIndex:'zone.name',editor:new Ext.form.TextField()},
            {header:'排序',width:100,sortable:true,dataIndex:'zone.position',editor:new Ext.form.NumberField()},
            {header:'编码',width:250,sortable:true,dataIndex:'zone.code',editor:new Ext.form.TextField()},
            {header:'区域下人口数',width:250,sortable:true,dataIndex:'zone.peopleNum',editor:new Ext.form.TextField({vtype:'integer',listeners:{
            		'focus':function(field){
            			var rec = grid.getSelectionModel().getSelected();
            			if(rec.data['zone.code'].length<11){
            				field.setReadOnly(true);
            			}
            			else{
            				field.setReadOnly(false);
            			}
            		}
            	}})}
            
        ],
        renderTo:'grid',
        border:true,
        clicksToEdit:2,
        selModel:new Ext.grid.RowSelectionModel()
    });
    
    ds.load({params:{parent_id:'0'}});
};

var buildLayout = function(){
    new Ext.Viewport({
        layout:'border',
        defaults:{border:false},
        items:[{
            region:'north',
            contentEl:'north-div',
            title:'区域设置',
            tbar:[{
                text:'新增',
                iconCls:'admin-tool-add',
                handler:createModule
            },'-',{
                text:'保存',
                iconCls:'admin-tool-save',
                handler:saveModule
            },'-',{
                text:'删除',
               iconCls:'admin-tool-delete',
                handler:destroyModule
            }]
        },{
            region:'west',
            width:280,
            split:true,
            autoScroll:true,
            items:tree
        },{
            region:'center',
            layout:'fit',
            items:grid
        }]
    });
};

var init = function(){
    buildTree();
    buildGrid();
  	buildLayout();
};

Ext.onReady(init);

var createModule = function(){
    var node = tree.getSelectionModel().getSelectedNode();
    if (node){
        Ext.Ajax.request({
            url:'zone!create.action',
            params:{
                parent_id:node.id,
                'zone.name':'新区域'
            },
            success:function(response){
                var data = Ext.util.JSON.decode(response.responseText);
                if (data.success){
                    node.appendChild(new Ext.tree.TreeNode({
                        id:data.id,
                        text:'新区域',
                        leaf:true
                    }));
                    node.getUI().removeClass('x-tree-node-leaf');
                    node.getUI().addClass('x-tree-node-expanded');
                    node.leaf = false;
                    node.expand();
                    ds.reload();
                }
                else{
                    Ext.MessageBox.alert('警告',data.msg);
                }
            }
        })
    }
};

var saveModule = function(){
	var records = ds.getModifiedRecords();
	for (var i = 0; i < records.length; i++) {
		var params = records[i].data;
    	if(tree.getSelectionModel().getSelectedNode().id>0)
    		params['zone.parent.id'] = tree.getSelectionModel().getSelectedNode().id;
		
        Ext.Ajax.request({
            url:'zone!update.action',
            params:params,
            method:'POST',
            success:function(response){
                var data = Ext.util.JSON.decode(response.responseText);
                var r = ds.getById(data.id);
				r.commit();
                var node = tree.getSelectionModel().getSelectedNode().findChild('id',data.id);
                if (node){
                    node.setText(data.name);
                }
            }
        });
	}
};
var destroyModule = function(){
	
	var rows = grid.getSelectionModel().getSelections();
	var node = tree.getSelectionModel().getSelectedNode();
	if (rows.length == 0 && (!node || node.id =='0')){
		Ext.Msg.alert("提示", "您还没有选择任何区域！");
		return;
	}
	
	if (rows.length == 0 && !node.isLeaf()) {
		Ext.Msg.alert("提示", "您选中的区域有子区域，请先删除子区域！");
		return;
	}
	Ext.MessageBox.confirm('请确认', '您确认删除这些记录吗？',function(btn){if(btn == 'yes'){
		var ids = [];
		if (rows.length > 0){
			for (var i = 0; i < rows.length; i++) {
				ids.push(rows[i].data['zone.id']);
			}
		}
		else{
			ids.push(node.id);
		}
		
	
		Ext.Ajax.request({
			url:'zone!delete.action',
			method:'POST',
			params:{'ids':ids},
			success:function(response){
				var data = Ext.util.JSON.decode(response.responseText);
				var rows = grid.getSelectionModel().getSelections();
				if (data.success){
					for(var i = 0 ;i < ids.length; i++){
						var id = ids[i];
						var snode = tree.getSelectionModel().getSelectedNode();
						if (snode.id == id){  //当前树节点是要删除的节点
							snode.remove();
			            }
			            else{ //通过id查找子节点
			            	var node = snode.findChild('id',id);
			                node.remove();
			            }
					}
							                
			        ds.reload();
			        Ext.MessageBox.alert('警告','删除区域资料完成。');
		        }
				else{
		            Ext.MessageBox.alert('警告',data.msg);
				}
			}
		});
	}});
}
